<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="房间ID" prop="roomId">
        <el-input
          v-model="queryParams.roomId"
          placeholder="请输入房间ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租客姓名" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入租客姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房东姓名" prop="landlordName">
        <el-input
          v-model="queryParams.landlordName"
          placeholder="请输入房东姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-input
          v-model="queryParams.paymentMethod"
          placeholder="请输入支付方式"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维修责任" prop="maintenanceTerms">
        <el-select v-model="queryParams.maintenanceTerms" placeholder="请选择维修责任" clearable>
          <el-option
            v-for="dict in maintenance_terms"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择合同状态" clearable>
          <el-option
            v-for="dict in tb_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['contracts:contracts:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['contracts:contracts:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['contracts:contracts:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['contracts:contracts:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同ID" align="center" prop="contractId" />
      <el-table-column label="房间ID" align="center" prop="roomId" />
      <el-table-column label="租客姓名" align="center" prop="tenantName" />
      <el-table-column label="租客身份证号" align="center" prop="tenantIdNumber" />
      <el-table-column label="租客电话" align="center" prop="tenantPhone" />
      <el-table-column label="房东姓名" align="center" prop="landlordName" />
      <el-table-column label="房东身份证号" align="center" prop="landlordIdNumber" />
      <el-table-column label="房东电话" align="center" prop="landlordPhone" />
      <el-table-column label="租期开始日期" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="租期结束日期" align="center" prop="endDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="每月租金" align="center" prop="monthlyRent" />
      <el-table-column label="押金" align="center" prop="deposit" />
      <el-table-column label="每月租金支付日期" align="center" prop="paymentDate" />
      <el-table-column label="支付方式" align="center" prop="paymentMethod" />
      <el-table-column label="其他费用承担方式" align="center" prop="utilityResponsibility" />
      <el-table-column label="房屋使用规定" align="center" prop="usageRestrictions" />
      <el-table-column label="维修责任" align="center" prop="maintenanceTerms">
        <template #default="scope">
          <dict-tag :options="maintenance_terms" :value="scope.row.maintenanceTerms"/>
        </template>
      </el-table-column>
      <el-table-column label="合同终止条件" align="center" prop="terminationConditions" />
      <el-table-column label="其他特殊约定" align="center" prop="specialClauses" />
      <el-table-column label="合同状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="tb_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['contracts:contracts:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['contracts:contracts:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改租赁合同对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="contractsRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="房间ID" prop="roomId">
          <el-input v-model="form.roomId" placeholder="请输入房间ID" />
        </el-form-item>
        <el-form-item label="租客姓名" prop="tenantName">
          <el-input v-model="form.tenantName" placeholder="请输入租客姓名" />
        </el-form-item>
        <el-form-item label="租客身份证号" prop="tenantIdNumber">
          <el-input v-model="form.tenantIdNumber" placeholder="请输入租客身份证号" />
        </el-form-item>
        <el-form-item label="租客电话" prop="tenantPhone">
          <el-input v-model="form.tenantPhone" placeholder="请输入租客电话" />
        </el-form-item>
        <el-form-item label="房东姓名" prop="landlordName">
          <el-input v-model="form.landlordName" placeholder="请输入房东姓名" />
        </el-form-item>
        <el-form-item label="房东身份证号" prop="landlordIdNumber">
          <el-input v-model="form.landlordIdNumber" placeholder="请输入房东身份证号" />
        </el-form-item>
        <el-form-item label="房东电话" prop="landlordPhone">
          <el-input v-model="form.landlordPhone" placeholder="请输入房东电话" />
        </el-form-item>
        <el-form-item label="租期开始日期" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择租期开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="租期结束日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择租期结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="每月租金" prop="monthlyRent">
          <el-input v-model="form.monthlyRent" placeholder="请输入每月租金" />
        </el-form-item>
        <el-form-item label="押金" prop="deposit">
          <el-input v-model="form.deposit" placeholder="请输入押金" />
        </el-form-item>
        <el-form-item label="每月支付日期" prop="paymentDate">
          <el-input v-model="form.paymentDate" placeholder="请输入每月租金支付日期" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-input v-model="form.paymentMethod" placeholder="请输入支付方式" />
        </el-form-item>
        <el-form-item label="水电费" prop="utilityResponsibility">
          <el-input v-model="form.utilityResponsibility" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="房屋使用规定" prop="usageRestrictions">
          <el-input v-model="form.usageRestrictions" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="维修责任" prop="maintenanceTerms">
          <el-radio-group v-model="form.maintenanceTerms">
            <el-radio
              v-for="dict in maintenance_terms"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="合同终止条件" prop="terminationConditions">
          <el-input v-model="form.terminationConditions" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="其他特殊约定" prop="specialClauses">
          <el-input v-model="form.specialClauses" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="合同状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in tb_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Contracts">
import { listContracts, getContracts, delContracts, addContracts, updateContracts } from "@/api/contracts/contracts";

const { proxy } = getCurrentInstance();
const { tb_status, maintenance_terms } = proxy.useDict('tb_status', 'maintenance_terms');

const contractsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roomId: null,
    tenantName: null,
    landlordName: null,
    paymentMethod: null,
    maintenanceTerms: null,
    specialClauses: null,
    status: null,
  },
  rules: {
    roomId: [
      { required: true, message: "房间ID不能为空", trigger: "blur" }
    ],
    tenantName: [
      { required: true, message: "租客姓名不能为空", trigger: "blur" }
    ],
    tenantIdNumber: [
      { required: true, message: "租客身份证号不能为空", trigger: "blur" }
    ],
    tenantPhone: [
      { required: true, message: "租客电话不能为空", trigger: "blur" }
    ],
    landlordName: [
      { required: true, message: "房东姓名不能为空", trigger: "blur" }
    ],
    landlordIdNumber: [
      { required: true, message: "房东身份证号不能为空", trigger: "blur" }
    ],
    landlordPhone: [
      { required: true, message: "房东电话不能为空", trigger: "blur" }
    ],
    startDate: [
      { required: true, message: "租期开始日期不能为空", trigger: "blur" }
    ],
    endDate: [
      { required: true, message: "租期结束日期不能为空", trigger: "blur" }
    ],
    monthlyRent: [
      { required: true, message: "每月租金不能为空", trigger: "blur" }
    ],
    deposit: [
      { required: true, message: "押金不能为空", trigger: "blur" }
    ],
    paymentDate: [
      { required: true, message: "每月租金支付日期不能为空", trigger: "blur" }
    ],
    paymentMethod: [
      { required: true, message: "支付方式不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "合同状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询租赁合同列表 */
function getList() {
  loading.value = true;
  listContracts(queryParams.value).then(response => {
    contractsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    contractId: null,
    roomId: null,
    tenantName: null,
    tenantIdNumber: null,
    tenantPhone: null,
    landlordName: null,
    landlordIdNumber: null,
    landlordPhone: null,
    startDate: null,
    endDate: null,
    monthlyRent: null,
    deposit: null,
    paymentDate: null,
    paymentMethod: null,
    utilityResponsibility: null,
    usageRestrictions: null,
    maintenanceTerms: null,
    terminationConditions: null,
    specialClauses: null,
    status: null,
    createdAt: null,
    updatedAt: null
  };
  proxy.resetForm("contractsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.contractId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加租赁合同";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _contractId = row.contractId || ids.value
  getContracts(_contractId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改租赁合同";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["contractsRef"].validate(valid => {
    if (valid) {
      if (form.value.contractId != null) {
        updateContracts(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addContracts(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _contractIds = row.contractId || ids.value;
  proxy.$modal.confirm('是否确认删除租赁合同编号为"' + _contractIds + '"的数据项？').then(function() {
    return delContracts(_contractIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('contracts/contracts/export', {
    ...queryParams.value
  }, `contracts_${new Date().getTime()}.xlsx`)
}

getList();
</script>
